<?php

namespace app\model;

use think\helper\Str;
use think\Model;
use think\model\relation\HasMany;

class Plateform extends Model
{
    public function product(): HasMany
    {
        return $this->hasMany(PlateformCode::class, "pid");
    }

    public function pageData(): array
    {
        $param = request()->param();
        $data = $this->withCount(['product'])->when(!empty($param['name']), function ($query) use ($param) {
            $query->whereLike("name", "%{$param['name']}%");
        })->when(!empty($param['mobile']), function ($query) use ($param) {
            $query->whereLike("mobile", "%{$param['mobile']}%");
        })->order(['create_time' => 'desc'])->paginate([
            "list_rows" => $param['pageSize'] ?? 30,
            "page" => $param['page'] ?? 1
        ])->toArray();
        return ['lst' => $data['data'], 'total' => $data['total']];
    }

    public function saveData(): array
    {
        $param = request()->param();
        if (!empty($param['password'])) {
            $password = setPassword($param['password']);
            $param['password'] = $password['password'];
            $param['encode'] = $password['encode'];
        } else {
            unset($param['password']);
        }
        if (empty($param['id'])) {
            $param['code'] = Str::random(12);
        }
        $count = $this->when(!empty($param['id']), function ($query) use ($param) {
            $query->where('id', '<>', $param['id']);
        })->when(!empty($param['mobile']), function ($query) use ($param) {
            $query->where('mobile', '=', $param['mobile']);
        })->count();
        if ($count > 0) throw new \Exception("手机号重复", 7002);
        $this->exists(!empty($param['id']))->save($param);
        return $this->toArray();
    }

    public function detail(): array
    {
        return $this->findOrFail(request()->param('id'))->toArray();
    }
}
